<template>
  <div id="employee-main-container" class="employee-index">
    <xr-header
      :show-search = "false"
      style="padding: 0px 15px 15px 0;"
      ft-top="0"
      icon-class="wk wk-user"
      icon-color="#2362FB"
      placeholder="请输入员工姓名"
      search-icon-type="icon"
      @search="searchClick" >
      <template slot="search">
        <el-input :value="searchText" style="margin: 0 auto; width: 200px" class="xr-header__search" placeholder="选择部门/员工" @focus.stop="membersDepVisible = true">
          <el-button
            slot="append"
            icon="el-icon-search"
            @click.native="refreshList"/>
        </el-input>
      </template>
      <template slot="label">
        周报管理
      </template>
      <template slot="ft">
        <el-button v-if="hasFilterContent" type="text" @click="resetFilter">清除筛选</el-button>
        <wk-popover-filter
          :width="popoverFilterWidth"
          :field-from.sync="filterObj"
          :field-list="filterList"
          :has-content="hasFilterContent"
          style="margin-right: 5px;"
          placement="bottom"
          @sure="refreshList"
          @reset="resetFilter"
        />
        <template>
          <el-popconfirm title="请选择周报模板" confirm-button-text="新媒体" cancel-button-text="品牌店铺" confirm-button-type="warning" cancel-button-type="success" @confirm="createClick('2')" @cancel="createClick('1')">
            <el-button
              slot="reference"
              icon="el-icon-plus"
              type="primary">新增汇报</el-button>
          </el-popconfirm>
        </template>
      </template>
    </xr-header>
    <div class="crm-container">
      <flexbox class="filter">
        <wk-border-menu
          :list="tabLeftList"
          :is-select="true"
          v-model="tabType"
          style="flex: 6;"
          @select="tabClick"
        />
      </flexbox>
      <xr-table-header
        v-if="selectionList.length > 0"
        :handles="tabelHandles"
        :selects="selectionList"
        @command="handleCommand" />
      <el-table
        v-loading="loading"
        id="crm-table"
        :row-height="40"
        :data="list"
        :height="tableHeight"
        :cell-class-name="cellClassName"
        use-virtual
        class="n-table--border el-table-header--white"
        stripe
        border
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick">
        <el-table-column
          :selectable="selectable"
          show-overflow-tooltip
          type="selection"
          align="center"
          width="55"/>
        <el-table-column
          v-for="(item, index) in fieldList"
          :key="index"
          :prop="item.fieldName"
          :label="item.name"
          :min-width="item.width"
          :formatter="fieldFormatter"
          align="center"
          show-overflow-tooltip/>
        <el-table-column
          prop="ownerUserList"
          label="汇报对象"
          min-width="200"
          align="center"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="control-item">
              <span
                v-for="(item, index) in getShowSendUserList(scope.$index)"
                :key="index"
                class="send-user">
                <el-tooltip
                  placement="bottom"
                  effect="light"
                  popper-class="tooltip-change-border">
                  <div slot="content">
                    <span>{{ item.realname || item.name }}</span>
                  </div>
                  <xr-avatar
                    :name="item.realname || item.name"
                    :size="32"
                    :src="item.img" />
                </el-tooltip>
              </span>
              <members-dep
                :content-block="false"
                :user-checked-data="sendUserList[scope.$index] || []"
                :close-dep="true"
                @popoverSubmit="users => sendUserChange(users, scope.$index)">
                <span slot="membersDep">
                  <el-button v-if="scope.row.submitStatus == 1" type="info" size="default" icon="el-icon-plus" circle />
                </span>
              </members-dep>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="200">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleRowClick(scope.row, undefined, 'detail')">详情</el-button>
            <el-button v-if="scope.row.submitStatus == 1" type="success" size="small" @click="submit(scope.row.id)">提交</el-button>
          </template>
        </el-table-column>
        <template slot="empty">
          <p>暂无数据</p>
          <el-popconfirm title="请选择周报模板" confirm-button-text="新媒体" cancel-button-text="品牌店铺" confirm-button-type="warning" cancel-button-type="success" @confirm="createClick('2')" @cancel="createClick('1')">
            <el-button
              slot="reference"
              icon="el-icon-plus"
              type="primary">新增汇报</el-button>
          </el-popconfirm>
        </template>
      </el-table>
      <div class="p-contianer">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size.sync="pageSize"
          :total="total"
          class="p-bar"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </div>
    <report-detail
      v-if="showDview"
      :id="rowID"
      @handle="detailHandle"
      @close="showDview=false"/>

    <report-create-view
      v-if="isCreate"
      :tab-type="reportType"
      @success="createSaveSuccess"
      @close="isCreate=false"/>

    <form-add-dialog
      ref="formAdddialog"
      :title="formAddTitle"
      :form.sync="formAddForm"
      :rules="formAddRules"
      :fields="formAddFields"
      :visible.sync="formAddDialogShow"
      @pass="formAddPass"
    />

    <!-- 员工部门选择 -->
    <members-dep-dialog
      :visible.sync="membersDepVisible"
      :dep-checked-data="filterValue.strucs"
      :user-checked-data="filterValue.users"
      :radio="true"
      @confirm="membersDepSelect"
    />
  </div>
</template>

<script>
import {
  executionReportPageListAPI,
  executionBrandReportAddAPI,
  executionReportDeleteAPI,
  executionReportSubmitAPI,
  executionReportStatusNumAPI,
  executionReportUpdateAPI
} from '@/api/oa/report'


import XrHeader from '@/components/XrHeader'
import XrTableHeader from '@/components/XrTableHeader'
import WkPopoverFilter from '@/components/NewCom/WkPopoverFilter'
import ReportCreateView from './components/ReportCreateView'
import ReportDetail from './ReportDetail'
import FormAddDialog from './components/FormAddDialog'
import WkBorderMenu from '../../hrm/components/WkBorderMenu'

import { mapGetters } from 'vuex'
import { reportTypeOptions, wekkOptions } from './model/report'
import moment from 'moment'
import MembersDepDialog from '@/components/SelectEmployee/MembersDepDialog'
import MembersDep from '@/components/SelectEmployee/MembersDep'

export default {
  name: 'ReportIndex',
  components: {
    XrHeader,
    XrTableHeader,
    ReportCreateView,
    ReportDetail,
    WkPopoverFilter,
    FormAddDialog,
    WkBorderMenu,
    MembersDepDialog,
    MembersDep
  },
  data() {
    return {
      loading: false, // 加载动画
      isCreate: false, // 是创建
      tableHeight: document.documentElement.clientHeight - 275, // 表的高度
      list: [],
      fieldList: [],
      // 性别、出生日期、年龄、入职日期、转正日期、部门、工号、生日
      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 60, 100],
      total: 0,
      search: '', // 搜索内容
      // 筛选宽
      tabType: 4,
      // 筛选条件
      tabLeftList: [{
        label: '未读汇报',
        name: 1,
        num: 0
      }, {
        label: '我提交的汇报',
        name: 2,
        num: 0
      }, {
        label: '最近一周汇报',
        name: 3,
        num: 0
      }, {
        label: '全部汇报',
        name: 4,
        num: 0
      }],
      /** 控制详情展示 */
      rowID: '', // 行信息
      showDview: false,
      selectionList: [], // 勾选数据 用于全局导出
      // 操作
      tabelHandles: [{
        label: '删除',
        command: 'delete',
        icon: 'wk wk-delete'
      }],
      // 弹窗添加
      formAddTitle: '',
      formAddForm: {},
      formAddRules: {},
      formAddFields: [],
      formAddDialogShow: false,
      // 编辑详情
      // 需要编辑的员工详情
      handleRowData: null,
      fieldSetLoading: false,
      // 筛选宽
      popoverFilterWidth: 150,
      filterObj: {}, // 筛选确定数据
      filterList: [{
        name: '月份',
        field: 'month',
        formType: 'month',
        setting: []
      }, {
        name: '周期',
        field: 'targetWeek',
        formType: 'select',
        setting: wekkOptions
      }],
      // 部门员工筛选
      membersDepVisible: false,
      searchText: '',
      filterValue: {
        users: [],
        strucs: []
      },
      // 汇报类型
      reportType: '1',
      // 汇报对象
      sendUserList: []
    }
  },
  computed: {
    ...mapGetters([
      'collapse'
    ]),
    // 有筛选内容
    hasFilterContent() {
      if (this.filterObj) {
        let hasContent = false
        const keys = Object.keys(this.filterObj)
        for (let index = 0; index < keys.length; index++) {
          const key = keys[index]
          if (this.filterObj[key] != '' &&
           this.filterObj[key] != [] &&
           this.filterObj[key] != null &&
           this.filterObj[key] != undefined) {
            hasContent = true
          }
        }
        return hasContent
      }
      return false
    }
  },
  watch: {
    collapse: {
      handler(val) {
        this.popoverFilterWidth = document.documentElement.clientWidth - (val ? 89 : 225)
      },
      immediate: true
    }
  },
  created() {
    window.onresize = () => {
      this.tableHeight = document.documentElement.clientHeight - (this.selectionList.length > 0 ? 325 : 275)
    }
    this.getStatusNum()
    this.getFieldList()
    this.refreshList()
    if (this.$route.query.id) {
      this.rowID = this.$route.query.id
      this.showDview = true
    }
  },
  methods: {
    getStatusNum() {
      executionReportStatusNumAPI().then(res => {
        const keys = Object.keys(res.data)
        this.tabLeftList.forEach(item => {
          item.num = res.data[keys.find(k => k == item.name)]
        })
      }).catch(e => {
        console.log(e)
      })
    },


    /**
     * 选择员工和部门
     */
    membersDepSelect(users, strucs) {
      if (!users.length && !strucs.length) {
        this.searchText = ''
        this.filterValue.users = []
        this.filterValue.strucs = []
        this.filterObj.createUserId = ''
        this.filterObj.deptId = ''
      } else {
        if (users.length > 0) {
          this.searchText = users[0].realname
          this.filterObj.createUserId = users[0].userId
          this.filterValue.users = users
          this.filterValue.strucs = []
          this.filterObj.deptId = ''
        } else if (strucs.length > 0) {
          this.searchText = strucs[0].name
          this.filterObj.deptId = strucs[0].id
          this.filterValue.strucs = strucs
          this.filterObj.createUserId = ''
          this.filterValue.users = []
        }
      }
      this.refreshList()
    },
    /**
     * 高级筛选
     */
    resetFilter() {
      this.filterObj = {}
      this.refreshList()
    },
    /**
     * 刷新当前页面信息
     */
    refreshPageData() {
      this.getList()
    },

    /**
     * tab点击
     */
    tabClick(tab) {
      this.filterObj = {
        targetYear: '',
        targetMonth: '',
        targetWeek: ''
      }
      this.refreshList()
    },

    /**
     * 新建
     */
    createClick(reportType) {
      this.handleRowData = null
      this.reportType = reportType
      this.isCreate = true
    },

    /**
     * 创建成功
     */
    createSaveSuccess() {
      this.refreshList()
    },

    /**
     * 搜索
     */
    searchClick(search) {
      this.search = search
      this.refreshList()
    },

    /**
     * 详情操作
     */
    detailHandle(data) {
      if (data.type === 'delete') {
        // 刷新当前人状态
        this.showDview = false
      }
      this.getList()
    },

    /**
     * 刷新
     */
    refreshList() {
      this.handleCurrentChange(1)
    },

    /**
     * 更改每页展示数量
     */
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    /**
     * 更改当前页数
     */
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    /**
     * 列表数据
     */
    getList() {
      this.loading = true

      const params = {
        page: this.currentPage,
        limit: this.pageSize,
        type: this.tabType
      }
      for (var key in this.filterObj) {
        if (key == 'month') {
          const split = this.filterObj[key].split('-')
          params.targetYear = split[0]
          params.targetMonth = split[1]
        } else {
          params[key] = this.filterObj[key]
        }
      }
      executionReportPageListAPI(params)
        .then(res => {
          this.list = res.data.list
          this.total = res.data.totalRow
          if (res.data.totalRow && Math.ceil(res.data.totalRow / this.pageSize) < this.currentPage && this.currentPage > 1) {
            this.currentPage = this.currentPage - 1
            this.getList()
          } else {
            this.total = res.data.totalRow
            this.loading = false
          }

          this.list.forEach((item, index) => {
            this.sendUserList[index] = item.ownerUserList
          })

          this.$nextTick(() => {
            const warpDom = document.querySelector('.el-table__body-wrapper')
            warpDom.scrollTop = 1
            if (warpDom.scrollLeft != 0) {
              warpDom.scrollLeft = warpDom.scrollLeft - 1
            }
          })
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 获取表头展示字段
     */
    getFieldList() {
      this.fieldList = [
        // { fieldName: 'id', name: 'ID', sortable: '', width: 100 },
        { fieldName: 'week', name: '周期', sortable: '', width: 100 },
        { fieldName: 'createUserName', name: '创建人', sortable: '', width: 100 },
        { fieldName: 'deptName', name: '部门', sortable: '', width: 100 },
        { fieldName: 'reportName', name: '汇报名称', sortable: '', width: 100 },
        // { fieldName: 'reportContent', name: '汇报内容', sortable: '', width: 100 },
        { fieldName: 'reportType', name: '汇报类型', sortable: '', width: 100 },
        { fieldName: 'submitStatus', name: '提交状态', sortable: '', width: 100 },
        { fieldName: 'submitTime', name: '提交时间', sortable: '', width: 100 }
        // { fieldName: 'ownerUserList', name: '汇报对象', sortable: '', width: 200 },
        // { fieldName: 'copyUserList', name: '抄送对象', sortable: '', width: 100 },
      ]
    },

    /**
     * 格式化字段
     */
    fieldFormatter(row, column) {
      if (column.property == 'week') {
        return row['targetYear'] + '年' + row['targetMonth'] + '月第' + row['targetWeek'] + '周' || '--'
      } else if (column.property == 'reportType') {
        return reportTypeOptions.find(item => item.value == row[column.property]).label || '--'
      } else if (column.property == 'submitTime') {
        return row[column.property] ? moment(row[column.property]).format('Y-M-D HH:mm') : '--'
      } else if (column.property == 'submitStatus') {
        // return row[column.property] == 1 ? '暂存' : (row[column.property] == 2 ? '按时提交' : '延迟补交')
        return row[column.property] == 1 ? '暂存' : '已提交'
      } else if (column.property == 'ownerUserList' || column.property == 'copyUserList') {
        return row[column.property] ? row[column.property].map(item => item.realname).toString() : '--'
      } else {
        return row[column.property] || '--'
      }
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property == 'reportName') {
        return 'can-visit--underline'
      } else {
        return ''
      }
    },

    /**
     * 勾选操作
     */
    handleSelectionChange(val) {
      this.selectionList = val // 勾选的行
      this.tableHeight = document.documentElement.clientHeight - (this.selectionList.length > 0 ? 325 : 275)
    },

    /**
     * 列表操作
     */
    handleCommand(command) {
      if (command === 'delete') {
        this.$confirm('确定要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            executionReportDeleteAPI(this.selectionList.map(item => item.id))
              .then(res => {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getList()
              })
              .catch(() => {})
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
      }
    },

    /**
     * 列表点击
     */
    handleRowClick(row, column, event) {
      if (event == 'detail' || column.property == 'reportName') {
        setTimeout(() => {
          this.getStatusNum()
        }, 500)
        this.rowID = row.id
        this.showDview = true
      }
    },

    /**
     * 弹窗确认操作
     */
    formAddPass() {
      this.$refs.formAdddialog.loading = true
      this.formAddForm.employeeId = this.handleRowData.id

      executionBrandReportAddAPI(this.formAddForm).then(res => {
        this.$refs.formAdddialog.loading = false
        this.$message.success(`${this.formAddTitle}成功`)
        this.formAddDialogShow = false
        this.getList()
      }).catch(() => {
        this.$refs.formAdddialog.loading = false
      })
    },
    /** 提交操作 */
    submit(id) {
      this.$confirm('请确认信息填写完整，否则将提交失败', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        executionReportSubmitAPI(id).then(res => {
          this.$message.success('提交成功')
          this.getList()
        }).catch(e => {
          console.log(e)
        })
      })
    },
    // 判断是否可以多选删除
    selectable(row, index) {
      if (row.submitStatus == 1) {
        return true
      }
      return false
    },
    /**
     * 汇报对象选择
     */
    sendUserChange(users, index) {
      this.sendUserList[index] = users
      this.list[index].ownerUserIds = users.map(item => item.userId).join(',')
      executionReportUpdateAPI(this.list[index]).then(res => {
        this.$message.success('修改成功')
        this.refreshList()
      }).catch(e => {
        console.log(e)
      })
    },
    /**
     * 汇报对象显示
     */
    getShowSendUserList(index) {
      const sendUserList = this.sendUserList[index] || []
      return sendUserList
    }
  }
}
</script>

<style lang="scss" scoped>
.employee-index {
  .xr-header {
    /deep/ .xr-header__ft {
      top: 0;
      line-height: 34px;
    }
  }

  /deep/.xr-table-header {
    border-bottom: 1px solid $xr-border-color-base;
    .xr-table-header__body {
      padding: 0;
    }
  }
  .search-button {
    border: none;

    &.is-select {
      background: $xr-color-primary;
      color: white;
    }
  }

  /deep/ .el-tabs {
    .el-tabs__header {
      margin-bottom: 0;
    }

    .el-tabs__item {
      color: #42526E;
      font-weight: bold;
    }
  }

  .tab-pane-num {
    background-color: #DFE1E6;
    border-radius: 10px;
    color: #42526E;
    display: inline-block;
    font-size: 12px;
    font-weight: bold;
    height: 18px;
    line-height: 18px;
    padding: 0 6px;
    text-align: center;
    white-space: nowrap;
    border: 1px solid #fff;
  }

  .table-more {
    cursor: pointer;
    &:hover {
      color: $xr-color-primary
    }
  }

  .filter {
    margin-bottom: 8px;
    width: 50%;
    .wk-border-menu {
      margin-left: 20px;
    }
  }

  // 汇报对象显示
  /deep/ .control-item {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-content: center;
  }
  /deep/ span.send-user {
      display: inline-block;
      margin-right: 5px;
  }
}
</style>
